import Vue from "vue";
import Vuex from "vuex"

Vue.use(Vuex);  //配置 vue 注册 vuex
export default new Vuex.Store({
    //定义全局数据
    state: {
        //维持用户登录状态
        user: {
            id: localStorage.getItem("id"),
            username: localStorage.getItem("username"),
            isAdmin: localStorage.getItem("isAdmin"),
            state: localStorage.getItem("state") //0正常(默认) 1禁言
        }
    },
    mutations: {
        //更新登录状态
        login(state, user) {
            state.user.id = user.id;
            state.user.username = user.username;
            state.user.isAdmin = user.isAdmin;
            state.user.state = user.state;
            //保存到 localStorage 中, 防止刷新页面，丢失 vuex 数据
            localStorage.setItem("id", user.id);
            localStorage.setItem("username", user.username);
            localStorage.setItem("isAdmin", user.isAdmin);
            localStorage.setItem("state", user.state);
        },
        //删除所有登录状态
        logout(state) {
            state.user = {};
            localStorage.clear();
        }
    },
});